package service

import (
	"app-webapi/comm/g"
	"app-webapi/entity"
	"github.com/gin-gonic/gin"
	"time"
)

var LogChannel = make(chan entity.OperationLog, 100)

//GenerateLog 生成日志
func GenerateLog(ctx *gin.Context, operationType int, operationContent string) {
	value, exists := ctx.Get("user")
	if !exists {
		return
	}
	user, ok := value.(*entity.Userinfo)
	if !ok {
		return
	}
	LogChannel <- entity.OperationLog{
		OperationTime:         time.Now(),
		OperationUserID:       int64(user.ID),
		OperationUserName:     user.Username,
		OperationUserRealName: user.RealName,
		OperationContent:      operationContent,
		OperationType:         operationType,
	}
}

//ConsumeLog 消费日志
func ConsumeLog() {
	defer func() {
		if err := recover(); err != nil {
			g.Logger.Error("ConsumeLog", err)
			ConsumeLog()
		}
	}()
	for {
		select {
		case log := <-LogChannel:
			g.Db.Create(&log)
		}
	}

}
